const accountDAO = require('../DAO/accountDAO.js');
const incomeDAO = require('../DAO/incomeDAO.js');
const { getOpenid } = require('../dbCloud.js');


const getAccountAllMonthNum = async () => {
  var userId = getOpenid();
  var result = await accountDAO.queryAllAccounts(userId);
  var resultMap = {};
  result.data.forEach(item => {
    var time = item.time;
    var arr = time.split('-');
    arr.pop();
    var yearMonth = arr.join('/');
    const accountVal = item.accountVal / 1 || 0;
    if (!resultMap[yearMonth]) {
      resultMap[yearMonth] = 0;
    }
    resultMap[yearMonth] += accountVal / 1;
  });
  return resultMap;
};

const getIncomeAllMonthNum = async () => {
  var result = await incomeDAO.queryAllIncomes(getOpenid());
  var resultMap = {};
  result.data.forEach(item => {
    var time = item.incomeTime;
    var arr = time.split('-');
    arr.pop();
    var yearMonth = arr.join('/');
    const incomeValue = item.incomeValue / 1 || 0;
    if (!resultMap[yearMonth]) {
      resultMap[yearMonth] = 0;
    }
    resultMap[yearMonth] += incomeValue / 1;
  });
  return resultMap;
};

/**
 * 获取各个月的额度
 */
const getAllMonthNum = async () => {
  var aMap = await getAccountAllMonthNum();
  var iMap = await getIncomeAllMonthNum();
  var aKeys = Object.keys(aMap);
  var iKeys = Object.keys(iMap);
  var map = {};
  aKeys.forEach(a => {
    map[a] = true;
  });
  iKeys.forEach(i => {
    map[i] = true;
  });
  var dateList = Object.keys(map);
  var list = [];
  dateList.forEach(date => {
    var name = date;
    var aVal = aMap[date];
    var iVal = iMap[date];
    list.push({
      name,
      aVal,
      iVal
    });
  });
  list = list.sort((a, b) => {
    return new Date(a.name).getTime() - new Date(b.name).getTime();
  });
  return list;
};

const getEngelCoefficient = async () => {
  var resultMap = {};
  var userId = getOpenid();
  var result = await accountDAO.queryAllAccounts(userId);

  result.data.forEach(item => {
    const accountVal = item.accountVal / 1 || 0;
    const accountType = item.accountType;
    if (!resultMap[accountType]) {
      resultMap[accountType] = 0;
    }
    resultMap[accountType] += accountVal / 1;
  });
  
  var total = 0;
  var footVal = resultMap[1];

  for (let key in resultMap) {
    total += resultMap[key] / 1;
  }
  return (footVal / total || 0).toFixed(2) ;
}

module.exports = {
  getAllMonthNum,
  getEngelCoefficient
};
